package com.kady.controller.front;

import com.alibaba.fastjson.JSON;
import com.kady.Dao.OrderDao;
import com.kady.contant.BeanFactoryConstant;
import com.kady.contant.ExceptionConstant;
import com.kady.contant.MessageConstant;
import com.kady.controller.BaseServlet;
import com.kady.entity.*;
import com.kady.factory.BeanFactory;
import com.kady.service.FrontService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/3/30
 * \* Time: 12:57
 * \* 千峰JAVA2101班
 * \* Description: 前端页面接口控制层
 * \
 */
@WebServlet("/front/data")
public class FrontController extends BaseServlet {
    private FrontService frontService = (FrontService) BeanFactory.getBean(BeanFactoryConstant.FRONT_SERVICE);

    /**
     * 获取餐桌
     */
    public String getTables(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        Object user = req.getSession().getAttribute("frontUser");
        /**
         * 如果有用户登录，判断用户是否有已下单的订单，如果有，需要让用户先去结账
         */
        if(user!=null){
            Order order = frontService.findUserHasNotOrdered(user);
            if(order!=null){
               ResultVO resultVO =  new ResultVO(false,ExceptionConstant.EXIST_NOT_ORDERED_ORDER);
               resultVO.setData(order.getOrderId());
                return JSON.toJSONString(resultVO);
            }
        }

        List<Table> list = frontService.getTableListByStatus();
        return JSON.toJSONString(list);
    }

    /**
     * 查询菜品列表 根据条件混合查询
     */
    public String getFoodList(HttpServletRequest req, HttpServletResponse resp) throws SQLException, InvocationTargetException, IllegalAccessException {
        String tableId = req.getParameter("tableId");
        String typeId = req.getParameter("typeId");
        String keyword = req.getParameter("keyword");
        String page = req.getParameter("page");
        /**
         * 设置桌号
         */
        if(tableId!=null){
            req.getSession().setAttribute("tableId",tableId);
        }

        /**
         * 获取菜单分页信息
         */
        page = page==null? "1" : page;
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(Long.valueOf(page));
        PageInfo resPageInfo = frontService.getFoodListByCondition("%" + (keyword==null?"":keyword.trim())+"%",pageInfo,typeId==""||typeId==null?null:typeId);
        req.getSession().setAttribute("foodListByPage",resPageInfo);

        /**
         * 获取菜系列表
         */
        List<FoodType> foodTypes = frontService.getFoodTypeList();

        /**
        * 传参回显
         */
        req.getSession().setAttribute("foodTypes",foodTypes);
        req.getSession().setAttribute("keyword",keyword);
        req.getSession().setAttribute("typeId",typeId);
        return MessageConstant.PREFIX_FORWARD + "/front/detail/caidan.jsp";
    }

    /**
     * 获取菜品详情
     */
    public String getFoodDetail(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String foodId = req.getParameter("foodId");
        Food food = frontService.getFoodDetail(foodId);
        req.setAttribute("foodDetail",food);
        return MessageConstant.PREFIX_FORWARD + "/front/detail/caixiangxi.jsp";
    }

    /**
     * 将菜品放入餐车
     */
    public String takeInToCart(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        Object user = req.getSession().getAttribute("frontUser");
        String foodId = req.getParameter("foodId");
        /**
         * 判断用户是否有登录，异步请求，前台提示跳转去登录
         */

        if(user==null){
            return JSON.toJSONString(new ResultVO(false, ExceptionConstant.USER_NOT_LOGIN));
        }
        /**
         * 判断是否有桌号
         */
        Object tableId = req.getSession().getAttribute("tableId");
        if(tableId==null){
            return JSON.toJSONString(new ResultVO(false, ExceptionConstant.NO_TABLE_ID));
        }

        /**
         * 判断是否已有下单未结账的订单，如果有，先去结账
         */
        Order order = frontService.findUserHasNotOrdered(user);
        if(order!=null){
            ResultVO resultVO =  new ResultVO(false,ExceptionConstant.EXIST_NOT_ORDERED_ORDER);
            resultVO.setData(order.getOrderId());
            return JSON.toJSONString(resultVO);
        }

        /**
         * 先判断有没有餐车，没有就创建
         */
        //获取餐车
        Cart cart = null;
        cart = (Cart) req.getSession().getAttribute("Cart-"+ ((User)user).getUser_id() + "-" + (String)tableId);
        if(cart==null){
            cart = new Cart();
        }

        Cart resCart = frontService.updateCart(cart,foodId,(User) user,1,true);

        /**
         * 把加好的餐车存回去
         */
        req.getSession().setAttribute("Cart-"+ ((User)user).getUser_id() + "-" + (String)tableId,cart);

        return JSON.toJSONString(new ResultVO(true,"添加成功"));

    }

    /**
     * 获取餐车
     */
    public Object getCart(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        Object user = req.getSession().getAttribute("frontUser");
        Object tableId = req.getSession().getAttribute("tableId");
        /**
         * 判断用户是否有登录，异步请求，前台提示跳转去登录
         * 判断是否有桌号
         * 封装
         */
        Object obj = checkUserAndTableId(req);
        if(obj!=null){
            return obj;
        }

        /**
         * 获取餐车数据
         */
        Cart cart = (Cart) req.getSession().getAttribute("Cart-"+ ((User)user).getUser_id() + "-" + (String)tableId);
        req.getSession().setAttribute("cartInfo",cart);
        return MessageConstant.PREFIX_FORWARD + "/front/detail/clientCart.jsp";
    }

    /**
     * 修改餐车
     */
    public Object updateCartItem(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String foodId = req.getParameter("foodId");
        String count = req.getParameter("count");
        Object user = req.getSession().getAttribute("frontUser");
        Object tableId = req.getSession().getAttribute("tableId");
        /**
         * 判断用户是否有登录，异步请求，前台提示跳转去登录
         * 判断是否有桌号
         * 封装
         */
        Object obj = checkUserAndTableId(req);
        if(obj!=null){
            return obj;
        }

        Cart cart = (Cart) req.getSession().getAttribute("Cart-"+ ((User)user).getUser_id() + "-" + (String)tableId);
        //修改餐车数量
        Cart resCart = frontService.updateCart(cart, foodId, (User) user, Long.valueOf(count), false);
        req.getSession().setAttribute("cartInfo",resCart);
        return MessageConstant.PREFIX_FORWARD + "/front/data?method=getCart";
    }

    /**
     * 删除餐车菜品
     */
    public Object deleteCartItem(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String foodId = req.getParameter("foodId");
        Object user = req.getSession().getAttribute("frontUser");
        Object tableId = req.getSession().getAttribute("tableId");
        /**
         * 判断用户是否有登录，异步请求，前台提示跳转去登录
         * 判断是否有桌号
         * 封装
         */
        Object obj = checkUserAndTableId(req);
        if(obj!=null){
            return obj;
        }
        Cart cart = (Cart) req.getSession().getAttribute("Cart-"+ ((User)user).getUser_id() + "-" + (String)tableId);
        //删除
        Cart resCart = frontService.updateCart(cart, foodId, (User) user, 0L, false);
        req.getSession().setAttribute("cartInfo",resCart);
        return MessageConstant.PREFIX_FORWARD + "/front/data?method=getCart";
    }

    /**
     * 下单
     */
    public Object makeOrder(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        Object user = req.getSession().getAttribute("frontUser");
        Object tableId = req.getSession().getAttribute("tableId");
        /**
         * 判断用户是否有登录，异步请求，前台提示跳转去登录
         * 判断是否有桌号
         * 封装
         */
        Object obj = checkUserAndTableId(req);
        if(obj!=null){
            return obj;
        }

        Cart cart = (Cart) req.getSession().getAttribute("Cart-"+ ((User)user).getUser_id() + "-" + (String)tableId);
        if(cart==null){
            return new ResultVO(false,ExceptionConstant.NO_CARTITEMS);
        }
        //下单
        String orderId = UUID.randomUUID().toString().replace("-","");
        frontService.setOrder(orderId,(User)user,(String)tableId,cart);
        req.getSession().removeAttribute("Cart-"+ ((User)user).getUser_id() + "-" + (String)tableId);
        req.getSession().setAttribute("orderId",orderId);
        return MessageConstant.PREFIX_FORWARD + "/front/data?method=getOrderList";
    }

    /**
     * 获取订单信息
     */
    public Object getOrderList(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, InvocationTargetException, IllegalAccessException {
        Object user = req.getSession().getAttribute("frontUser");
        /**
         * 判断用户是否有登录，异步请求，前台提示跳转去登录
         */
        if(user==null){
            return new ResultVO(false, ExceptionConstant.USER_NOT_LOGIN);
        }
        /**
         * 进来时判断用户是否有下单，有下单先进来结账,
         */
        String notOrderedId = req.getParameter("orderId");
        Object orderId = req.getSession().getAttribute("orderId");
        //有未结账的使用notOrderedId，生成的订单用orderId
        Cart resCart = frontService.getOrderCart(notOrderedId!=null?notOrderedId:(String)orderId,(User) user);
        req.setAttribute("orderId",notOrderedId!=null?notOrderedId:(String)orderId);
        req.getSession().setAttribute("orderInfo",resCart);
        return MessageConstant.PREFIX_FORWARD + "/front/detail/clientOrderList.jsp";
    }

    /**
     * 结账
     */
    public Object settle(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        Object user = req.getSession().getAttribute("frontUser");
        String orderId = req.getParameter("orderId");
        if(orderId==null){
            return new ResultVO(false,ExceptionConstant.NOT_FIND_ORDER_ID);
        }
        long res = frontService.settleOrder(orderId);
        if(res>0){
            /**
             * 结账完成删除餐桌ID、餐车信息 和 订单信息
             */
            req.getSession().removeAttribute("tableId");
            req.getSession().removeAttribute("cartInfo");
            req.getSession().removeAttribute("orderInfo");
            req.getSession().removeAttribute("orderId");
            return "<script>alert('"+ MessageConstant.FINISH_INFO +"');window.location.href = 'index.jsp'</script>";
        }
        return MessageConstant.PREFIX_FORWARD + "/front/detail/clientOrderList.jsp";
    }

    public Object checkUserAndTableId (HttpServletRequest req){
        Object user = req.getSession().getAttribute("frontUser");
        /**
         * 判断用户是否有登录，异步请求，前台提示跳转去登录
         */
        if(user==null){
            return new ResultVO(false, ExceptionConstant.USER_NOT_LOGIN);
        }
        /**
         * 判断是否有桌号
         */
        Object tableId = req.getSession().getAttribute("tableId");
        if(tableId==null){
            return JSON.toJSONString(new ResultVO(false, ExceptionConstant.NO_TABLE_ID));
        }
        return null;
    }

}
